import router from './index'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login'] // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const token = userStore.token
  
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 检查token是否过期
      if (!userStore.checkTokenExpire()) {
        next('/login')
        NProgress.done()
        return
      }

      // 判断是否已获取用户信息
      if (Object.keys(userStore.userInfo).length === 0) {
        try {
          await userStore.getInfo()
          next({ ...to, replace: true })
        } catch (error) {
          await userStore.logout()
          next('/login')
        }
      } else {
        next()
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
}) 